package com.qd.p2p.web.action.borrow;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Qualifier;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.*;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.exception.BorrowException;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.*;
import com.qdlc.p2p.dal.model.AccountModel;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.model.BorrowRepaymentModel;
import com.qdlc.p2p.dal.model.UserCreditApplyModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 我的借款
 *
 * @author cx
 * @version 2.0
 *          2014-10-30
 */
@SuppressWarnings("rawtypes")
public class MyBorrowAction extends BaseAction implements ModelDriven<BorrowModel> {

    private BorrowModel model = new BorrowModel();

    @Override
    public BorrowModel getModel() {
        return model;
    }

    @Resource
    private BorrowRepaymentService borrowRepaymentService;

    @Resource
    private UserCreditService userCreditService;

    @Resource
    private UserCreditApplyService userCreditApplyService;

    @Resource
    private BorrowService borrowService;

    @Resource
    private AccountService accountService;

    @Resource
    private UserService userService;

    private User user;

    private Map<String, Object> data;

    @Resource
    @Qualifier("borrowRepayCollectService")
    private CollectPayService borrowRepayCollectService;

    /**
     * 查看正在借款项目详情
     *
     * @return
     * @throws Exception
     */
    @Action("/member_borrow/borrow/mine")
    public String mine() throws Exception {
        checkBorrowUser();
        String status = request.getParameter("status");
        if (status != null) {
            request.setAttribute("status", status);
        }
        return "mine";
    }

    /**
     * 我的借款列表 ajax数据接口 status(标状态) start_time end_time(开始结束时间) name(标名)
     *
     * @return
     */
    @Action("/member/borrow/mineList")
    public void mineList() throws Exception {
        user = getSessionUser();
        model.setUser(user);
        model.setIps(false);
        PageDataList<BorrowModel> pageDataList = borrowService.getList(model);
        data = new HashMap<String, Object>();
        data.put("data", pageDataList);
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 撤标 初审之前
     *
     * @throws Exception if has error
     */
    @Action("/member/borrow/cancel")
    public void cancel() throws Exception {
        Borrow borrow = borrowService.find(model.getId());
        borrow.setRepaymentAccount(-1); //标记前台撤标
        borrowService.cancel(borrow);
        frontRedirect("/member/borrow/mine.html"); //重定向到撤标之后的页面
    }

    /**
     * 我的待还
     *
     * @return String
     * @throws Exception if has error
     */
    @Action(value = "/member_borrow/borrow/repayment")
    public String repayment() throws Exception {
        checkBorrowUser();
        request.setAttribute("borrowId", paramLong("borrowId"));
        return "mine";
    }

    /**
     * 我的待还列表 ajax数据接口 status 0待还 1已还 start_time end_time (发布时间) name 标名
     *
     * @return
     * @throws Exception if has error
     */
    @Action("/member/borrow/repaymentList")
    public void repaymentList() throws Exception {
        user = getSessionUser();
        BorrowRepaymentModel m = (BorrowRepaymentModel) paramModel(BorrowRepaymentModel.class);
        m.setBorrowId(paramLong("borrowId"));
        m.setUser(user);
        int status = this.paramInt("status");
        m.setStatus(status);
        PageDataList<BorrowRepaymentModel> pageDataList = borrowRepaymentService.getList(m);
        Account account = accountService.findAccountByUserId(this.getSessionUserId());
        data = new HashMap<String, Object>();
        data.put("data", pageDataList);
        data.put("account", account);
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 判断是否已设置交易密码
     *
     * @return
     * @throws Exception
     */
    @Action(value = "/member/borrow/checkPayPassword")
    public String checkPayPassword() throws Exception {
        data = new HashMap<String, Object>();
        User newUser = userService.getUserByUserName(getSessionUser().getUserName());

        boolean result = newUser.getPayPwd() == null ? false : true;

        data.put("result", result);
        printWebJson(getStringOfJpaObj(data));
        return null;
    }

    /**
     * PS 还款
     *
     * @throws Exception if has error
     */
    @Action("/member/borrow/repay")
    public void repay() throws Exception {
        User newUser = userService.getUserByUserName(getSessionUser().getUserName());
        String validCode = paramString("validCode");
        // 校验验证码是否正确,防止重复点击
        model.validBorrowCode(validCode);
        // 支付密码是否正确
        model.checkPayPwd(newUser);

        // 还款信息
        BorrowRepayment borrowRepayment = borrowRepaymentService.findById(model.getRepaymentId());
        // 校验是否当前本人操作还款
        User sessionUser = getSessionUser();
        if (null == borrowRepayment || !sessionUser.getUserName().equals(borrowRepayment.getUser().getUserName())) {
            throw new BorrowException("还款信息异常", BorrowException.TYPE_JSON);
        }

        // 正常还款 余额是否充足判断
        //int period = borrowRepayment.getPeriod(); // 期数
        //double upRateSum = upRateCollectionDao.upRateCollectionSum(borrowRepayment.getBorrow().getId(), period);
        // 本期还款额
        double repayTotalAmount = BigDecimalUtil.add(borrowRepayment.getRepaymentAccount());

        // 校验可用余额是否充足
        Account account = accountService.findAccountByUserId(newUser.getUserId());
        if (repayTotalAmount > account.getUseMoney()) {
            throw new BorrowException("可用余额不足,请先充值后再操作!", BorrowException.TYPE_JSON);
        }

   /*     // 第三方可用余额判断
        TppModel tppModel = new TppModel();
        tppModel.setUser(newUser);
        TppBaseInterface tppService = TppServiceFactory.newIntance();
        TppAccountModel tppAccount = (TppAccountModel) tppService.tppQueryBalance(tppModel);
        double useMoney = Double.valueOf(tppAccount.getUserMoney()).doubleValue();
        if (repayTotalAmount > useMoney) {
            throw new BorrowException(MessageFormat.format("您的托管资金可用余额不足,请先充值后再操作!托管资金余额:{0}", useMoney), BorrowException.TYPE_JSON);
        }*/

        // 还款
        doRepay(borrowRepayment);

        long borrowId = borrowRepayment.getBorrow().getId();
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("bid", borrowId);
        data.put("result", true);
        printWebJson(getStringOfJpaObj(data));
    }

    void doRepay(BorrowRepayment borrowRepayment) {
        List<TppTradeLog> tppTradeLogs = borrowRepayCollectService.createOrders(borrowRepayment);
        for(TppTradeLog tppTradeLog : tppTradeLogs){
            ReturnResult returnResult = borrowRepayCollectService.requestOrder(tppTradeLog);
            if (returnResult.isError()) {
                throw new BusinessException("系统繁忙,请稍候重试!", BusinessException.TYPE_JSON);
            }
        }
    }


    /**
     * 前台逾期还款
     *
     * @throws Exception
     */
    @Action("/member/borrow/overduePayment")
    public void overduePayment() throws Exception {
        user = getSessionUser();
        model.checkPayPwd(user);
        BorrowRepayment borrowRepayment = borrowRepaymentService.findById(model.getRepaymentId());
        borrowService.overduePayment(borrowRepayment);
        printWebSuccess();
    }

    /**
     * 提前还款
     *
     * @throws Exception if has error
     */
    @Action("/member/borrow/doPriorRepay")
    public void doPriorRepay() throws Exception {
        user = getSessionUser();
        model.checkPayPwd(user);
        BorrowRepayment borrowRepayment = borrowRepaymentService.findById(model.getRepaymentId());
        borrowService.doPriorRepay(borrowRepayment);
        printWebSuccess();
    }

    /**
     * 下载协议
     *
     * @return
     */
    @Action("/member/borrow/protocol")
    public String protocol() throws Exception {
        checkBorrowUser();
        return null;
    }

    /**
     * 信用额度页面
     */
    @Action("/member_borrow/borrow/creditApply")
    public String creditApply() throws Exception {
        user = getSessionUser();
        checkBorrowUser();
        long userId = user.getUserId();
        // 申请中
        int applyIngCount = userCreditApplyService.count(userId, 2);
        // 申请记录
        request.setAttribute("applyIngCount", applyIngCount);
        return "creditApply";
    }

    /**
     * 新增信用额度页面
     */
    @Action("/member_borrow/borrow/addApply")
    public String addApply() throws Exception {
        user = getSessionUser();
        checkBorrowUser();
        long userId = user.getUserId();
        // 申请中
        int applyIngCount = userCreditApplyService.count(userId, 2);
        // 申请记录
        request.setAttribute("applyIngCount", applyIngCount);
        return "addApply";
    }


    /**
     * 信用额度列表
     *
     * @throws Exception
     */
    @Action("/member/borrow/creditApplyList")
    public void creditApplyList() throws Exception {
        user = getSessionUser();
        long userId = user.getUserId();
        PageDataList<UserCreditApply> applyList = userCreditApplyService.list(userId, model);
        data = new HashMap<String, Object>();
        data.put("data", applyList);
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 信用额度申请
     *
     * @throws Exception
     */
    @Action("/member/borrow/doCreditApply")
    public void doCreditApply() throws Exception {
        user = getSessionUser();
        checkBorrowUser();
        AccountModel accountModel = new AccountModel();
        // 申请中
        int applyIngCount = userCreditApplyService.count(user.getUserId(), 2);
        UserIdentify userIdentify = UserUtils.getUserIdentify(user);
        accountModel.validAttestionForAmountApply(userIdentify, model.getAmount(), applyIngCount);
        UserCredit uCredit = userCreditService.findByUserId(user.getUserId());
        UserCreditApplyModel userCreditApplyModel = new UserCreditApplyModel();
        userCreditApplyModel.validRemarkAndContentForAmountApply(model.getRemark(), model.getContent());
        String content = model.getContent().replaceAll("<", "%");
        String modelContent = content.replaceAll(">", "%");
        UserCreditApply CreditApply = new UserCreditApply(user, model.getAmount(), 2, uCredit, modelContent, model.getRemark());
        userCreditService.applyUserCredit(CreditApply);
        printWebSuccess();
    }
}
